// Importing required modules
const express = require('express');
// Creating an instance of Express.js
const app = express();
// Define a sample API endpoint
app.get('/api/example', (req, res) => {
// Sample response data
const responseData = {
message: 'This is a sample API endpoint!',
timestamp: new Date()
};
// Sending JSON response
res.json(responseData);
});
// Define port number
const port = 3000;
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
In this example:
- We import the Express.js module.
- We create an instance of the Express application.
- We define an API endpoint with the
GET
method at the route/api/example
. - When a request is made to
/api/example
, the server responds with a JSON object containing a message and a timestamp. - We specify the port number to listen on (in this case, 3000).
- We start the server, and it listens for incoming requests.
You can run this script using Node.js, and it will start a server listening on port 3000. When you navigate to http://localhost:3000/api/example
in your browser or make a GET request to that URL using a tool like cURL or Postman, you’ll receive a JSON response with the sample message and timestamp.